package net.sf.xoperator.ui.aiml;

import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import net.sf.xoperator.rdfxmpp.SPARQLQuery;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.openbbs.blackboard.ks.KSExecutionContext;

import bitoflife.chatterbean.Match;
/**
 * This class constructs the query string from the template and the parameters.
 * @author joerg
 *
 */
public class TemplateListener extends ExternalListener {
	
	
	private String wildcardRegEx = "\\%\\%\\d{1}\\%\\%";
	
	private Pattern wildcardPattern = Pattern.compile(wildcardRegEx);
	
	public TemplateListener() {
		super("query");

	}



	private Log log = LogFactory.getLog(TemplateListener.class);
	

	
	
	/**
	 * replaces all the wildcards in the query via regex
	 */
	@Override
	public String perform(Match match, String param) {
		KSExecutionContext context = ((BlackBoardContext)match.getCallback().getContext()).getContext();
		
		
		String result = param;
		Matcher matcher = wildcardPattern.matcher(result);
		while(matcher.find()){
			String matchString = matcher.group();
			int index = Integer.parseInt(matchString.substring(2,3));
			//fetch the content from the matcher
			result = matcher.replaceFirst(match.wildcard(Match.Section.PATTERN,index).trim());
			matcher = wildcardPattern.matcher(result);

		}
		
		context.blackboard().write(new SPARQLQuery(result));
		
		return "";
	}
	

}
